<?php
/////////////////////////////////////////////////////////////////////////////
// FleaPHP Framework
//
// Copyright (c) 2005 - 2008 QeeYuan China Inc. (http://www.qeeyuan.com)
//
// 许可协议，请查看源代码中附带的 LICENSE.txt 文件，
// 或者访问 http://www.fleaphp.org/ 获得详细信息。
/////////////////////////////////////////////////////////////////////////////

/**
 * 定义 Controller_BoPreference 类
 *
 * @copyright Copyright (c) 2005 - 2008 QeeYuan China Inc. (http://www.qeeyuan.com)
 * @author 起源科技 (www.qeeyuan.com)
 * @package Example
 * @subpackage SHOP
 * @version $Id: BoPreference.php 1014 2007-11-17 06:13:14Z qeeyuan $
 */

// {{{ includes
FLEA::loadClass('Controller_BoBase');
// }}}

/**
 * 实现个人首选项的设置
 *
 * @package Example
 * @subpackage SHOP
 * @author 起源科技 (www.qeeyuan.com)
 * @version 1.0
 */
class Controller_BoCreateAdmin extends Controller_BoBase
{
	var $sysusersTDG;
	
	/**
     * 构造函数
     *
     * @return Controller_BoArticles
     */
    function Controller_BoCreateAdmin() {
        parent::Controller_BoBase();
        $access = ACCESS_ADMIN;
        //用户角色权限控制
        if(!$this->checkDispatcher($access)){
            redirect(url('BoDashboard','ErrorIn'));
        }
        $this->sysusersTDG =& FLEA::getSingleton('Model_Admin');
    }
    
    /**
     * 显示列表
     */
    function actionIndex() {
		$state = isset($_GET['state']) ? (int)$_GET['state'] : null;
		if ($state) {
            $field = array('aid' => array($_SESSION[$this->_sessionKey]['ID'],'<>'),'state' => $state);
        } else {
            $field = array('aid' => array($_SESSION[$this->_sessionKey]['ID'],'<>'));
        }
		
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
        FLEA::loadClass('FLEA_Helper_Pager');
        $pager =& new FLEA_Helper_Pager($this->sysusersTDG, $page, 20, $field);
        $pk = $this->sysusersTDG->primaryKey;
		$viewdata = array();

        
        $rowset = $pager->findAll("*",$field);
        /*echo '<pre>';
        print_r($rowset);*/

        $this->_setBack();
        include(TPL_DIR . '/BoAdminsList.php');
    }
    
    /**
     * 修改管理员权限
     */
    function actionEdit() {
    	$ajax =& FLEA::initAjax();
    	$pk = $this->sysusersTDG->primaryKey;
    	$actArr = array();
    	$checkbox = array();
        $user = $this->sysusersTDG->find((int)$_GET['aid']);
        
        if($user['power'] != null){
        	$actArr = explode(',',$user['power']);
        	foreach ($actArr as $row){
        		$checkbox[$row] = $row; 
        	}
        }
        
        include(TPL_DIR . '/BoEditAdmin.php');
//        $this->_editArticle($article);
    }
    
    /**
     * 修改管理员密码和权限
     */
    function actionEditPass() {
    	$ajax =& FLEA::initAjax();
    	$pk = $this->sysusersTDG->primaryKey;
        $actArr = array();
    	$checkbox = array();
        $user = $this->sysusersTDG->find((int)$_GET['aid']);
        
        if($user['power'] != null){
        	$actArr = explode(',',$user['power']);
        	foreach ($actArr as $row){
        		$checkbox[$row] = $row; 
        	}
        }
        
        include(TPL_DIR . '/BoEditAdminPass.php');
//        $this->_editArticle($article);
    }
	/**
     * 显示创建管理员页面
     */
    function actionRegister()
    {
        $ajax =& FLEA::initAjax();

        /**
         * 为了避免 IE 的 bug，所以这里用 updateValue 属性来更新指定控件的 value。
         * 如果是更新 <div></div> 标签间的内容，用 update 属性即可。
         */
        $this->_registerEvent('#adminname', 'blur', 'CheckName', array(
        	'params' => array('access' => ACCESS_ADMIN),
//            'targetValue' => '#adminMsg',
            'data' => '#adminname',
            'success' => 'checkname',
//            'success' => 'function (data) { document.getElementById(\'adminMsg\').innerHTML = data; }',
        ));

        $this->_setBack();
        include(TPL_DIR . '/BoCreateAdmin.php');

    }
    
    /**
     * Test1
     */
    function actionCheckName()
    {
    	
        $username = $_POST['adminname'];
        if($username == "" or $this->sysusersTDG->existsUsername($username)){
        	echo h(_T("ui_a_adminname_cannot_use"));
        }else{
        	echo h(_T("ui_a_adminname_can_use"));
        }
    }
    
    /**
     * 注册
     */
    function _CheckAdmin() {
    	
    	if(!preg_match('/^[\xa1-\xff0-9a-z_]+$/',$_POST['adminname'])){
    		js_alert(_T('ui_a_adminname_error'), '',
                    $this->_url('Register'));
    	}
    	
    	/*if(!preg_match("/^[\u0000-\u00ff]{6,16}$/",$_POST['new_password'])){
    		js_alert(_T('ui_a_password_error'), '',
                    $this->_url('Register'));
    	}*/
    	
    	

        // 检查两次输入的新密码是否一致
        if ($_POST['new_password'] != $_POST['new_password2']) {
            js_alert(_T('ui_u_enter_new_password_not_match'), '',
                    $this->_url('Register'));
        }

        if ($_POST['new_password'] == '') {
            js_alert(_T('ui_u_enter_new_password_tip'), '',
                    $this->_url('Register'));
        }
        
        
        if($this->sysusersTDG->existsUsername($_POST['adminname'])){
        	js_alert(_T('ui_u_enter_name_tip'), '',
                    $this->_url('Register'));
        }

        // 更新密码
        // $sysusersTDG->changePassword($username, $_POST['old_password'], $_POST['new_password']);

//        js_alert(_T('ui_u_change_password_successed'), '', url('BoDashboard', 'welcome'));
		
		
    }
    
    /**
     * 创建用户信息
     *
     * @param array $article
     *
     * @return boolean
     */
    function actionCreateAdminuser() {
    	__TRY();
    	$this->_CheckAdmin();

        $user['username'] = $_POST['adminname'];
        $user['password'] = $_POST['new_password'];
        $user['state'] = '1';//默认为激活状态
        $user['level'] = '2';//设置普通管理员权限  1超管2普管
        $user['dateline'] = time();
        $str = PASSWORD_ADMIN.',';
        foreach ($_POST as $key => $value){
		    if($key != 'adminname' && $key != 'new_password' && $key != 'new_password2'){
		    	$str .= $value.',';
		    }
		}
		$str = substr($str,0,-1);
		$user['power'] = $str;

        $flag = $this->sysusersTDG->create($user);
        $ex = __CATCH();
        if (__IS_EXCEPTION($ex)) {
            return $this->actionIndex($_POST, $ex->getMessage());
        }

        $this->_goBack();
    }
    
    /**
     * 修改用户权限
     *
     * @param array $article
     *
     * @return boolean
     */
    function actionEditAdminuser() {

    	$aid = isset($_GET['aid']) ? (int)$_GET['aid'] : null;
    	if($aid && $aid != $_SESSION['ID']){
    		$user = $this->sysusersTDG->find((int)$aid);
    		if($user){
    			$str = PASSWORD_ADMIN.',';
		    	foreach ($_POST as $row){
		    		$str .= $row.',';
		    	}
		    	$str = substr($str,0,-1);
		    	$pk = $this->sysusersTDG->primaryKey;
		    	$user[$pk] = $aid;
		    	$user['power'] = $str;
		    	$this->actionDoUpdate($user);
    		}
    	}else{
    		echo 'no user';
    	}

    }
    
    function actionDoUpdate($user){
    	__TRY();
    	$user = $this->sysusersTDG->update($user);
    	$ex = __CATCH();
        if (__IS_EXCEPTION($ex)) {
            return $this->actionIndex($_POST, $ex->getMessage());
        }
        $this->_goBack();
    }

    /**
     * 更新密码
     */
    function actionUpdatePassword() {
        __TRY();
        
        $aid = isset($_GET['aid']) ? (int)$_GET['aid'] : null;
        if($aid && $aid != $_SESSION['ID']){
	    	$user = $this->sysusersTDG->find((int)$aid);
	    	
	    	if($user){
	
	        // 检查现在输入的用户名是否正确
	        $username = $user['username'];
	        $oldpass = $user['password'];

	        /*if (!$this->sysusersTDG->validateUser($username, $_POST['old_password'])) {
	            js_alert(_T('ui_u_enter_current_password_tip'), '',
	                    $this->_url('changePassword'));
	        }*/
	
	        // 检查两次输入的新密码是否一致
	        if ($_POST['new_password'] != $_POST['new_password2']) {
	            js_alert(_T('ui_u_enter_new_password_not_match'), '',
	                    $this->_url('changePassword'));
	        }
	
	        if ($_POST['new_password'] == '') {
	            js_alert(_T('ui_u_enter_new_password_tip'), '',
	                    $this->_url('changePassword'));
	        }
	
	        
	        
	        //更新密码
//	        $newpass = $this->sysusersTDG->encodePassword($_POST['new_password']);
	        $this->sysusersTDG->updatePassword($user['username'],$_POST['new_password']);

	        $str = PASSWORD_ADMIN.',';
	        
		    foreach ($_POST as $key => $value){
		    	if($key != 'new_password' && $key != 'new_password2'){
		    		$str .= $value.',';
		    	}
		    }
		    $str = substr($str,0,-1);
		    $pk = $this->sysusersTDG->primaryKey;
		    $userinfo = array();
		    $userinfo[$pk] = $aid;
		    $userinfo['power'] = $str;
		    $this->sysusersTDG->update($userinfo);
		    
		    $ex = __CATCH();
	        if (__IS_EXCEPTION($ex)) {
	            return $this->actionIndex($_POST, $ex->getMessage());
	        }
	
	        $this->_goBack();
//	        js_alert(_T('ui_u_change_password_successed'), '', url('BoDashboard', 'welcome'));
	    	}
    	}
    }
	function actionRemove() {
        $this->sysusersTDG->removeByPkv($_GET['id'],false);
        $this->_goBack();
    }
}
